package craky.keeper.category;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import craky.component.CommonTableModel;
import craky.component.JImagePane;
import craky.componentc.JCButton;
import craky.componentc.JCDialog;
import craky.componentc.JCMenuItem;
import craky.componentc.JCMessageBox;
import craky.componentc.JCPopupMenu;
import craky.componentc.JCScrollTable;
import craky.componentc.JCTable;
import craky.componentc.JCTableHeader;
import craky.keeper.KeeperApp;
import craky.layout.LineLayout;
import craky.util.UIUtil;

public class CategoryListDialog extends JCDialog {
	private static final long serialVersionUID = 8014695984667696577L;
	private KeeperApp keeper;
	private JComponent content;
	private Action addAction;
	private Action deleteAction;
	private Action cancelAction;
	private CommonTableModel<Category> model;
	private JCTable table;
	private JCPopupMenu popup;
	private Map<String, Category> categoryMap;
	private Category currentCategory;
	private boolean categoryUpdated;

	public CategoryListDialog(KeeperApp keeper) {
		super(keeper.getMainFrame(), "消费类别", Dialog.ModalityType.DOCUMENT_MODAL);
		this.keeper = keeper;
		initActions();
		initUI();
		setVisible(true);
	}

	private void initActions() {
		this.addAction = new AbstractAction("添加") {
			private static final long serialVersionUID = 5023433496740700046L;

			public void actionPerformed(ActionEvent e) {
				CategoryInfoDialog infoDialog = new CategoryInfoDialog(
						CategoryListDialog.this.keeper,
						CategoryListDialog.this, null);
				Category category = infoDialog.getCategory();

				if (category != null) {
					CategoryListDialog.this.model.insertRowData(category);
					CategoryListDialog.this.categoryMap.put(category.getName(),
							category);
					CategoryListDialog.this.categoryUpdated = true;
				}
			}
		};
		this.deleteAction = new AbstractAction("删除") {
			private static final long serialVersionUID = -568444344420944269L;

			public void actionPerformed(ActionEvent e) {
				CategoryListDialog dialog = CategoryListDialog.this;
				String title = "删除消费类别";
				String info = "确定要删除该消费类别吗？";

				if (JCMessageBox.createQuestionMessageBox(dialog, title, info)
						.open() == 4) {
					info = "消费类别删除成功＄1�7";
					CategoryDAO
							.deleteCategory(CategoryListDialog.this.currentCategory);
					CategoryListDialog.this.categoryMap
							.remove(CategoryListDialog.this.currentCategory
									.getName());
					CategoryListDialog.this.model
							.delRowData(CategoryListDialog.this.currentCategory);
					JCMessageBox.createInformationMessageBox(dialog, title,
							info).open();
					CategoryListDialog.this.categoryUpdated = true;
				}
			}
		};
		this.cancelAction = new AbstractAction("取消") {
			private static final long serialVersionUID = -568444344420944269L;

			public void actionPerformed(ActionEvent e) {
				CategoryListDialog.this.close();
			}
		};
		this.deleteAction.setEnabled(false);
	}

	private void initUI() {
		String[] columnsName = { "名称", "类型" };
		@SuppressWarnings("rawtypes")
		Class[] columnsClass = { String.class, String.class };
		String[] getMethodsName = { "getName", "getTypeName" };
		String[] setMethodsName = { "setName", "setTypeName" };
		JImagePane buttonPane = new JImagePane();
		this.content = ((JComponent) getContentPane());
		JCButton btnAdd = new JCButton(this.addAction);
		JCButton btnDelete = new JCButton(this.deleteAction);
		JCButton btnCancel = new JCButton(this.cancelAction);
		List<Category> categoryList = new ArrayList<Category>(
				(this.categoryMap = this.keeper.getCategoryMap()).values());
		JCScrollTable scTable = new JCScrollTable();
		this.table = scTable.getTable();
		JCTableHeader header = (JCTableHeader) this.table.getTableHeader();
		this.model = new CommonTableModel<Category>(scTable.getTable(),
				columnsName, columnsClass, getMethodsName, setMethodsName,
				categoryList);
		this.popup = new JCPopupMenu();
		JCMenuItem miDelete = new JCMenuItem(this.deleteAction);

		this.content.setPreferredSize(new Dimension(300, 350));
		this.content.setBorder(new EmptyBorder(0, 2, 2, 2));
		this.content.setLayout(new BorderLayout());
		scTable.setColumnControlEnabled(false);
		header.setShowPopupMenu(false);
		header.setReorderingAllowed(false);
		header.setResizingAllowed(false);
		this.table.setModel(this.model);
		this.table.setDragEnabled(false);
		this.table.setAutoResizeMode(4);
		this.table.setSelectionMode(0);
		this.table.setAutoCreateRowSorter(true);
		buttonPane.setLayout(new LineLayout(5, 7, 7, 7, 0, 10, 10, 0));
		buttonPane.setBackground(new Color(255, 255, 255, 150));
		buttonPane.setPreferredSize(new Dimension(-1, 32));
		btnAdd.setPreferredSize(new Dimension(69, 21));
		btnDelete.setPreferredSize(btnAdd.getPreferredSize());
		btnCancel.setPreferredSize(btnAdd.getPreferredSize());
		miDelete.setMnemonic('D');
		miDelete.setText(miDelete.getText() + "(D)");

		this.popup.add(miDelete);
		buttonPane.add(btnDelete, "End");
		buttonPane.add(btnAdd, "End");
		buttonPane.add(btnCancel, "End");
		this.content.add(buttonPane, "South");
		this.content.add(scTable, "Center");
		setDefaultCloseOperation(0);
		pack();
		setResizable(false);
		setLocationRelativeTo(getOwner());
		UIUtil.escAndEnterAction(this, btnAdd, this.cancelAction);

		this.table.getSelectionModel().addListSelectionListener(
				new ListSelectionListener() {
					public void valueChanged(ListSelectionEvent e) {
						CategoryListDialog.this.whenSelectionChanged(e);
					}
				});
		this.table.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				CategoryListDialog.this.select(e);
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				CategoryListDialog.this.showPopupMenu(e);
			}
		});
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				CategoryListDialog.this.close();
			}
		});
	}

	private void close() {
		if (this.categoryUpdated) {
			this.keeper.getMainFrame().updateCategory();
			this.categoryUpdated = false;
		}

		dispose();
	}

	private void whenSelectionChanged(ListSelectionEvent e) {
		this.currentCategory = (this.table.getSelectedRow() < 0 ? null
				: this.model.getSelectedRowData());
		this.deleteAction.setEnabled((this.currentCategory != null)
				&& (this.currentCategory.getType() != 0)
				&& (this.currentCategory.getCount() == 0L));
	}

	private void select(MouseEvent e) {
		int row = this.table.rowAtPoint(e.getPoint());

		if ((row >= 0) && (SwingUtilities.isRightMouseButton(e))) {
			this.table.getSelectionModel().setSelectionInterval(row, row);
		} else if ((row < 0) && (!SwingUtilities.isMiddleMouseButton(e))) {
			this.table.clearSelection();
		}
	}

	private void showPopupMenu(MouseEvent e) {
		int row = this.table.rowAtPoint(e.getPoint());

		if ((row >= 0) && (SwingUtilities.isRightMouseButton(e))) {
			this.popup.show((Component) e.getSource(), e.getX(), e.getY());
		}
	}
}